
// 获取子节点，一个数组
const getChildrenOne = (data, parentId, level) => {
  const arr = []
  // 查找子集
  const opts = data.filter(item => item.parentId == parentId)
  // 添加子集
  for (let i = 0; i < opts.length; i++) {
    // 遍历arr
    arr.push({
      value: opts[i].value,
      label: opts[i].label,
      children: [...getChildrenOne(data, opts[i].value, level + 1)]
    })
    if (arr[arr.length - 1].children.length === 0) {
      // arr[arr.length-1].leaf = true
      delete arr[arr.length - 1].children
    }
  }
  return arr
}

// 获取子节点，多个数组
const getChildren = (data, parentId, level) => {
  const arr = []
  // 记录最大层数
  const maxLevel = data.levelName.length

  if (maxLevel === level) {
    // 没有下一级了
    return arr
  } else {
    // 记录本级的名称
    const levelName = data.levelName[level]
    // 依据父ID查找子集
    const opts = data[levelName].filter(item => item.parentId === parentId)

    // 遍历添加
    for (let i = 0; i < opts.length; i++) {
      // 遍历arr
      arr.push({
        value: opts[i].value,
        label: opts[i].label + '-son',
        children: [...getChildren(data, opts[i].value, level + 1)]
      })
      // 没有children ，删除
      if (arr[arr.length - 1].children.length === 0) {
        delete arr[arr.length - 1].children
      }
    }
    return arr
  }
}

// 递归，浅层转嵌套
const shallowToDeep = (data) => {
  const arr = []
  if(!data){
    return arr
  }
  // 记录每一级的名称
  const levelName = data.levelName
  const opts = data[levelName[0]]
  for (let i = 0; i < opts.length; i++) {
    arr.push({
      value: opts[i].value,
      label: opts[i].label + '-top',
      children: [...getChildren(data, opts[i].value, 1)]
    })
    if (arr[arr.length - 1].children.length === 0) {
      delete arr[arr.length - 1].children
    }
  }
  return arr
}

const cascaderManage = (data) => {
  // let id = 0

  const levelName = data.levelName
  // const options = []

  // 级联需要的属性 props
  const propsCascader = {
    // multiple: false, // 单选还是多选 多选返回 value 的二维数组
    lazy: false, // 动态级联
    lazyLoad (node, resolve) { // 响应函数
      const { level } = node
      // 判断级数是否超过数组下标
      if (levelName.length >= level) {
        // 找到子数据-
        const key = levelName[level]
        const newNode = data[key].filter((item) => item.parentId === node.value)
        resolve(newNode) // 交给组件
      } else {
        resolve([{
          value: '22',
          label: '选项11',
          leaf: true
        }])
      }
    }
  }

  return {
    propsCascader
  }
}

export {
  getChildrenOne,
  getChildren,
  shallowToDeep,
  cascaderManage
}